<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { useUserInfoStore } from '@/stores/userInfo';
import { ElMessage } from 'element-plus';
import { userLogin, userRegister } from '@/api/user';

const router = useRouter();
const userInfoStore = useUserInfoStore();

const isRegister = ref(false);

// ✅ 登录表单
const loginForm = reactive({
  username: '',
  password: ''
});

// ✅ 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  rePassword: ''
});

// 校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5-16位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度为6-16位', trigger: 'blur' }
  ],
  rePassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value) => value === registerForm.password,
      message: '两次密码不一致',
      trigger: 'blur'
    }
  ]
};

// 提交处理
// /src/views/Login.vue (修改后)
// /src/views/Login.vue

// 请用这个函数完整替换你原来的 handleLogin
const handleLogin = async () => {
  try {


    const res = await userLogin({
      username: loginForm.username,
      password: loginForm.password
    });
    console.log('登录响应原始数据:', JSON.stringify(res));

    // res 的范例: { success: true, message: "登录成功", data: "5f6f9834..." }

    if (res.success && res.data) {


      ElMessage.success(res.message);

      // 把 res.data (那一长串真正的Token) 传递给 store！
      await userInfoStore.loginSuccess(res.data);

    } else {
      // 如果登录失败，比如密码错误，res.message 会是 "登录失败"
      ElMessage.error(res.message || '登录失败，请检查用户名或密码');
    }
  } catch (err) {
    // request.js 已经处理了网络异常等错误提示
    console.error('Login request failed:', err);
  }
};

const handleRegister = async () => {
  console.log('Register Data:', registerForm); // ✅ 调试
  try {
    const res = await userRegister({
      username: registerForm.username,
      password: registerForm.password
    });
    if (res.success) {
      ElMessage.success('注册成功');
      isRegister.value = false;
    } else {
      ElMessage.error(res.message || '注册失败');
    }
  } catch (err) {
    console.error('Register Error:', err);
    ElMessage.error('注册请求失败');
  }
};
</script>

<template>
  <el-row class="login-container">
    <el-col :span="8" :offset="8" class="login-form">
      <el-form
          ref="loginFormRef"
          v-if="!isRegister"
          :model="loginForm"
          :rules="rules"
          size="large"
      >
        <h2>登录</h2>
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="密码"
          />
        </el-form-item>
        <el-button type="primary" @click="handleLogin" block>
          登录
        </el-button>
        <el-link type="primary" @click="isRegister = true">没有账号？注册 →</el-link>
      </el-form>

      <el-form
          ref="registerFormRef"
          v-else
          :model="registerForm"
          :rules="rules"
          size="large"
      >
        <h2>注册</h2>
        <el-form-item prop="username">
          <el-input v-model="registerForm.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="密码"
          />
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input
              v-model="registerForm.rePassword"
              type="password"
              placeholder="确认密码"
          />
        </el-form-item>
        <el-button type="primary" @click="handleRegister" block>
          注册
        </el-button>
        <el-link type="primary" @click="isRegister = false">← 已有账号？登录</el-link>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(to right, #f5f7fa, #c3cfe2);
}

.login-form {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
  max-width: 400px;
  width: 100%;
}
</style>